import { _decorator, find, sp, v3, Vec3 } from "cc";
import { oops } from "db://oops-framework/core/Oops";
import { ecs } from "db://oops-framework/libs/ecs/ECS";
import { CCComp } from "db://oops-framework/module/common/CCComp";
import { Role } from "../../../role/Role";

const { ccclass, property } = _decorator;

/** BUFF特效 */
@ccclass('BuffViewComp')
@ecs.register('BuffView', false)
export class BuffViewComp extends CCComp {
    private spine!: sp.Skeleton;

    reset(): void {
        if (this.node)
            this.node.destroy();
    }

       // 加载动画
       load(target: Role, anim: any) {
        // 获取动画路径
        var path = `content/buff/${anim.anim}`;
        // 加载动画资源
        oops.res.load(path, sp.SkeletonData, (err: Error, sd: sp.SkeletonData) => {
            // 如果加载失败
            if (err) {
                console.error(`加载【${path}】的 SPINE 资源不存在`);
                return;
            }
            // 如果节点不存在或无效或目标不存在或目标视图不存在
            if (!this.node || !this.node.isValid || !target || !target.RoleView) return;

            // 设置节点父节点
            this.node.parent = find("content/buff", target.RoleView.node);
            // 如果动画是眩晕
            if(anim.anim == "xuanyun/buff_xuanyun"){
                // 获取眩晕位置
                var pos = this.getYunPos(find("content/spine", target.RoleView.node)!.getComponent(sp.Skeleton)!);
                // 设置节点位置
                this.node.setPosition(pos);
            }else{
                // 否则设置节点位置为(0,0,0)
                this.node.setPosition(v3(0, 0, 0));
            }
            // 获取节点上的spine组件
            this.spine = this.getComponent(sp.Skeleton)!;
            // 设置spine组件的skeletonData
            this.spine.skeletonData = sd;

            // 如果动画不循环
            if (anim.loop == 0)
                // 设置动画
                this.spine.setAnimation(0, "animation", false);
            else
                // 设置动画循环
                this.spine.setAnimation(0, "animation", true);
        });
    }


    getYunPos(_spine: sp.Skeleton): Vec3{
        var name = `yun_1`;
        var bone = _spine.findBone(name);
        if (bone) {
            var pos = v3(bone.worldX, bone.worldY);
            pos.x *= _spine.node.scale.x;
            pos.y *= _spine.node.scale.y;
            return pos;
        }
        else {
            console.warn(`编号为【名为【${name}】攻击点不存在`);
            return v3(0, 100, 0);
        }
    }
}